import CommonApi from 'services/commonApi';

import WxWebUtil from 'utils/wxWebUtil';

export default class MapUtil {
  static getLocationData(user) {
    if (process.env.isMiniprogram) {
      return this.getMiniprogramLocationData(user.openid).then(location=>{
        return location;
      });
    }

    return this.getWechartLocationData();
  }

  static getMiniprogramLocationData(openId) {
    return new window.Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        success: res => {
          CommonApi.getLocationData(openId, {
            longitude: res.longitude,
            latitude: res.latitude,
          }).then(location => {
            resolve(location);
          }).catch(error => {
            reject(error);
          });
        },
        fail: () => {
          CommonApi.getLocationData(openId, {
            longitude: 120.65518,
            latitude: 27.77838,
          }, true).then(location => {
            resolve(location);
          }).catch(error => {
            reject(error);
          });
        }
      });
    });
  }

  static async getWechartLocationData() {
    let config = await WxWebUtil.initWxConfig();
    return new window.Promise((resolve, reject) => {
      if (config instanceof Error) {
        reject(config);
        return;
      }

      CommonApi.getLocationData(config.appid, {
        longitude: 116.40000858848066,
        latitude: 39.91197393983452,
      }).then(location => {
        resolve(location);
      }).catch(error => {
        reject(error);
      });

      // wx.ready(() => {
      //   wx.getLocation({
      //     type: 'gcj02',
      //     success: res => {
      //       CommonApi.getLocationData(config.appid, {
      //         longitude: res.longitude,
      //         latitude: res.latitude,
      //       }).then(location => {
      //         resolve(location);
      //       }).catch(error => {
      //         reject(error);
      //       });
      //     },
      //     fail: error => {
      //       reject(error);
      //     }
      //   });
      // });
    });
  }
}
